package com.attendance.www.hr.service.impl;

import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;

import org.apache.commons.lang3.StringUtils;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.springframework.stereotype.Service;

import com.attendance.www.hr.beans.AttachmentBean;
import com.attendance.www.hr.beans.UserBean;
import com.attendance.www.hr.constant.AppConstant;
import com.attendance.www.hr.dao.mapper.EmployeeExtMapper;
import com.attendance.www.hr.dao.mapper.EmployeeMapper;
import com.attendance.www.hr.dao.mapper.UserExtMapper;
import com.attendance.www.hr.dao.mapper.UserMapper;
import com.attendance.www.hr.entitys.Employee;
import com.attendance.www.hr.entitys.User;
import com.attendance.www.hr.entitys.UserExample;
import com.attendance.www.hr.enums.PrivilegeGroupEnum;
import com.attendance.www.hr.exception.ResultFaultException;
import com.attendance.www.hr.service.IUserExcelService;
import com.zhangkongli.frame.utils.MD5Util;

@Service
public class UserExcelServiceImpl implements IUserExcelService {

	@Resource
	private UserMapper userDao;
	@Resource
	private EmployeeMapper employeeDao;
	@Resource
	private EmployeeExtMapper employeeExtDao;
	@Resource
	private UserExtMapper userExtDao;
	/**
	 * 数据库实体map
	 */
	private Map<String, UserBean> userMap;
	/**
	 * 导入表原员工no Map
	 */
	private Map<String, Integer> usernameMap;
	/**
	 * 导入表员工no Map
	 */
	private Map<String, Integer> employeeNoMap;
	/**
	 * 导入表全部员工no Map
	 */
	private Map<String, Integer> employeeNoAllMap;
	/**
	 * 导入表全部员工no Map
	 */
	private Map<String, Employee> employeeNoEntitysAllMap;

	/**
	 * 删除公司相关数据
	 * 
	 * @return
	 */
	@Override
	public boolean delUser() {
		return true;
	}

	@Override
	public List<String> importUser(Workbook work, AttachmentBean attachmentBean) {
		Calendar calendar = Calendar.getInstance(); // 得到日历
		calendar.setTime(attachmentBean.getFromDate());// 把当前时间赋给日历
		calendar.add(Calendar.DAY_OF_MONTH, -1); // 设置为前一天
		Date ThruDate = calendar.getTime(); // 得到前一天的时间
		Date oldThruDate = null;
		if (attachmentBean.getType() == 3) {
			UserExample example = new UserExample();
			UserExample.Criteria criteria = example.createCriteria();
			criteria.andThruDateIsNull();
			User user = new User();
			user.setThruDate(ThruDate);
			userDao.updateByExampleSelective(user, example);
		}
		
		userMap = new HashMap<String, UserBean>();
		usernameMap = new HashMap<String, Integer>();
		employeeNoMap = new HashMap<String, Integer>();
		employeeNoAllMap = new HashMap<String, Integer>();
		employeeNoEntitysAllMap = new HashMap<String, Employee>();

		List<String> successList = new ArrayList<String>();

		// 判断导入类型 1.覆盖 2.增量
		List<UserBean> userBeanList = userExtDao.getUserList(attachmentBean.getFromDate(),attachmentBean.getFromDate());
		for(UserBean user:userBeanList){
			userMap.put(user.getEmployeeNo(), user);
			employeeNoMap.put(user.getEmployeeNo(), -1);
			usernameMap.put(user.getUserName(), -1);
			oldThruDate = user.getThruDate();
		}
		List<Employee> employeeList = employeeExtDao.getEmployeeList(attachmentBean.getFromDate(), attachmentBean.getFromDate());
		for (Employee employee : employeeList) {
			employeeNoAllMap.put(employee.getEmployeeNo(), 1);
			employeeNoEntitysAllMap.put(employee.getEmployeeNo(), employee);
		}

		// 获取工作表的数量
		int sheetNum = work.getNumberOfSheets();
		// 遍历工作表 找出要导入的Excel表
		for (int m = 0; m < sheetNum; m++) {
			Sheet sh = work.getSheetAt(m);
			if (sh.getSheetName().equals("1.2用户表")) {
				Sheet sheet = work.getSheetAt(m);
				List<String> errorMsgList = new ArrayList<String>();// 创建错误信息列表
				// 扫描Excel每行的每个单元格
				for (int i = 1; i <= sheet.getLastRowNum(); i++) {
					User user = new User();// 创建公司对象
					StringBuilder str = new StringBuilder("第" + (i + 1) + "行");
					Row row = sheet.getRow(i);
					// 如果一整行为空则忽略此行继续遍历
					if (row == null) {
						continue;
					}
					// 遍历某一行的所有列，如果此行每列都为空则跳过继续下一行
					boolean isNull = true;
					for (int c = 0; c < row.getLastCellNum(); c++) {
						if (row.getCell(c) == null || StringUtils.isBlank(row.getCell(c).toString())) {
							continue;
						} else {
							isNull = false;
						}
					}
					if (isNull) {
						continue;
					}
					if (oldThruDate != null) {
						if (oldThruDate.getTime() >= attachmentBean.getFromDate().getTime()) {
							user.setThruDate(oldThruDate);
						}
					}
					user.setFromDate(attachmentBean.getFromDate());
					// 判断第一列员工号的合法性
					if (row.getCell(0) != null && StringUtils.isNotBlank(row.getCell(0).toString())) {
						String employeeNo = row.getCell(0).toString();
						if (employeeNoAllMap.containsKey(employeeNo)) {
							if (attachmentBean.getType()==1) {
								user.setEmployeeId(employeeNoEntitysAllMap.get(employeeNo).getEmployeeId());
								employeeNoMap.put(employeeNo, i + 1);
							} else {
								if (employeeNoMap.containsKey(employeeNo)) {
									if (employeeNoMap.get(employeeNo) < 0) {
										str.append("员工编码(" + employeeNo + ")已存在,");
									} else {
										str.append(
												"与第" + employeeNoMap.get(employeeNo) + "行员工编码(" + employeeNo + ")重复,");
									}
								} else {
									user.setEmployeeId(employeeNoEntitysAllMap.get(employeeNo).getEmployeeId());
									user.setCreateTime(employeeNoEntitysAllMap.get(employeeNo).getCreateTime());
									employeeNoMap.put(employeeNo, i + 1);
								}
							}
						} else {
							str.append("员工编码不存在,");
						}
					} else {
						str.append("员工编码不能为空,");
					}

					// 判断第二列用户名的合法性
					if (row.getCell(1) != null && StringUtils.isNotBlank(row.getCell(1).toString())) {
						String userName = row.getCell(1).toString();
						if (attachmentBean.getType()==1 && row.getCell(0) != null
								&& StringUtils.isNotBlank(row.getCell(0).toString())) {
							String employeeNo = row.getCell(0).toString();
							if(userMap.containsKey(employeeNo)) {
								if (userMap.get(employeeNo).getUserName().equals(userName)) {
									user.setUsername(userName);
									usernameMap.put(user.getUsername(), i + 1);
								} else if (usernameMap.containsKey(userName)) {
									if (usernameMap.get(userName) > 0) {
										str.append("与第" + usernameMap.get(userName) + "行用户名(" + userName + ")重复,");
									} else {
										str.append("用户名(" + userName + ")已存在,");
									}

								} else {
									user.setUsername(userName);
									usernameMap.put(user.getUsername(), i + 1);
								}
							}
							
						} else {
							if (usernameMap.containsKey(userName)) {
								if (usernameMap.get(userName) > 0) {
									str.append("与第" + usernameMap.get(userName) + "行用户名(" + userName + ")重复,");
								} else {
									str.append("用户名(" + userName + ")已存在,");
								}

							} else {
								user.setUsername(userName);
							}
						}
					} else {
						str.append("用户名不能为空,");
					}

					// 判断第二列中文名的合法性
					if (row.getCell(2) != null && StringUtils.isNotBlank(row.getCell(2).toString())) {
						Integer privilegeGroupId = PrivilegeGroupEnum.getName(row.getCell(2).toString());
						if (privilegeGroupId != null) {
							user.setPrivilegeGroupId(privilegeGroupId);
						} else {
							str.append("所属权限组格式不正确,");
						}
					}

					if (str.length() == new String("第" + (i + 1) + "行").length()) {
						MD5Util md5 = new MD5Util();
						String mdPassWord = md5.getMD5ofStr(AppConstant.PASSWORD);
						user.setPassword(mdPassWord);
						// 判断导入类型 1.覆盖 2.增量
						if (attachmentBean.getType()==1) {
							boolean t = true;
							if (user.getEmployeeId() != null) {
								user.setUpdateTime(new Date());
								userDao.updateByPrimaryKeySelective(user);
								String success = str.toString() + "员工编号(" + row.getCell(0).toString() + ")";
								successList.add(success);
								t = false;
							}
							if (t) {
								try {
									// 添加
									userDao.insertSelective(user);
								} catch (Exception e) {
									throw new ResultFaultException("9_00002");
								}
							}
						} else {
							try {
								// 添加
								userDao.insertSelective(user);
							} catch (Exception e) {
								throw new ResultFaultException("9_00002");
							}
						}
						UserBean userBean = new UserBean();
						userBean.setEmployeeNo(row.getCell(0).toString());
						userBean.setEmployeeId(user.getEmployeeId());
						userBean.setUserName(user.getUsername());

						userMap.put(userBean.getEmployeeNo(), userBean);

					} else {
						String errorStr = str.toString().substring(0, str.toString().length() - 1);
						errorMsgList.add(errorStr);
					}
				}
				if (errorMsgList.size() > 0) {
					throw new ResultFaultException("9_00002", errorMsgList);
				}

				if (successList.size() > 0) {
					successList.add(0, "用户导入完成,并覆盖数据如下：");
				} else {
					successList.add(0, "用户导入完成");
				}
				return successList;
			}
		}
		throw new ResultFaultException("9_00012");
	}
}
